import mongoose, { Schema, Document } from 'mongoose';

/**
 * 团队成员接口
 */
export interface ITeamMember {
  user: mongoose.Types.ObjectId;
  role: string; // 团队内角色
  joinedAt: Date;
}

/**
 * 团队接口定义
 */
export interface ITeam extends Document {
  name: string;
  slug: string;
  description?: string;
  organization: mongoose.Types.ObjectId;
  parent?: mongoose.Types.ObjectId; // 父团队（支持层级结构）
  leader: mongoose.Types.ObjectId; // 团队负责人
  members: ITeamMember[]; // 团队成员
  permissions: string[]; // 团队级别的权限
  settings: {
    isPublic: boolean;
    autoAssignTickets: boolean;
    notificationChannels: string[];
  };
  metadata?: {
    department?: string;
    location?: string;
    costCenter?: string;
  };
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

/**
 * 团队成员 Schema
 */
const TeamMemberSchema = new Schema<ITeamMember>(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    role: {
      type: String,
      required: true,
      enum: ['leader', 'member', 'viewer'],
      default: 'member'
    },
    joinedAt: {
      type: Date,
      default: Date.now
    }
  },
  { _id: false }
);

/**
 * 团队 Schema
 */
const TeamSchema = new Schema<ITeam>(
  {
    name: {
      type: String,
      required: [true, 'Team name is required'],
      trim: true,
      minlength: [2, 'Team name must be at least 2 characters'],
      maxlength: [100, 'Team name cannot exceed 100 characters']
    },
    slug: {
      type: String,
      required: true,
      lowercase: true,
      trim: true,
      match: [/^[a-z0-9-]+$/, 'Slug can only contain lowercase letters, numbers and hyphens']
    },
    description: {
      type: String,
      maxlength: [500, 'Description cannot exceed 500 characters']
    },
    organization: {
      type: Schema.Types.ObjectId,
      ref: 'Organization',
      required: true
    },
    parent: {
      type: Schema.Types.ObjectId,
      ref: 'Team',
      default: null
    },
    leader: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    members: [TeamMemberSchema],
    permissions: [{
      type: String
    }],
    settings: {
      isPublic: {
        type: Boolean,
        default: false
      },
      autoAssignTickets: {
        type: Boolean,
        default: false
      },
      notificationChannels: [{
        type: String,
        enum: ['email', 'slack', 'dingtalk', 'webhook']
      }]
    },
    metadata: {
      department: String,
      location: String,
      costCenter: String
    },
    isActive: {
      type: Boolean,
      default: true
    }
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
  }
);

// 复合索引
TeamSchema.index({ organization: 1, slug: 1 }, { unique: true });
TeamSchema.index({ organization: 1, isActive: 1 });
TeamSchema.index({ leader: 1 });
TeamSchema.index({ 'members.user': 1 });

// 虚拟字段：成员数量
TeamSchema.virtual('memberCount').get(function(this: ITeam) {
  return this.members.length;
});

// 虚拟字段：子团队
TeamSchema.virtual('children', {
  ref: 'Team',
  localField: '_id',
  foreignField: 'parent'
});

// 实例方法：检查用户是否是团队成员
TeamSchema.methods.isMember = function(userId: string): boolean {
  return this.members.some(member => member.user.toString() === userId.toString());
};

// 实例方法：检查用户是否是团队负责人
TeamSchema.methods.isLeader = function(userId: string): boolean {
  return this.leader.toString() === userId.toString();
};

// 实例方法：获取用户在团队中的角色
TeamSchema.methods.getMemberRole = function(userId: string): string | null {
  const member = this.members.find(m => m.user.toString() === userId.toString());
  return member ? member.role : null;
};

// 实例方法：添加成员
TeamSchema.methods.addMember = function(userId: mongoose.Types.ObjectId, role: string = 'member') {
  if (!this.isMember(userId.toString())) {
    this.members.push({
      user: userId,
      role,
      joinedAt: new Date()
    });
  }
};

// 实例方法：移除成员
TeamSchema.methods.removeMember = function(userId: string) {
  this.members = this.members.filter(member => member.user.toString() !== userId.toString());
};

// 静态方法：查找用户所在的所有团队
TeamSchema.statics.findTeamsByUser = function(userId: string, organizationId?: string) {
  const query: any = {
    'members.user': userId,
    isActive: true
  };

  if (organizationId) {
    query.organization = organizationId;
  }

  return this.find(query)
    .populate('organization', 'name slug')
    .populate('leader', 'username email');
};

// 静态方法：查找组织下的所有团队
TeamSchema.statics.findByOrganization = function(organizationId: string) {
  return this.find({ organization: organizationId, isActive: true })
    .populate('leader', 'username email')
    .sort({ createdAt: -1 });
};

const Team = mongoose.model<ITeam>('Team', TeamSchema);

export default Team;
